const db = require('../db');
const moment = require('moment');
const express = require('express');
const jwt = require("jsonwebtoken");
const config = require("../config");
const inspector = require("inspector");
const auditRouter = express.Router();

/*  数据表定义
CREATE TABLE audits (
  aud_id INT PRIMARY KEY AUTO_INCREMENT,
  order_id INT NOT NULL,
  aud_status ENUM('待审核', '通过', '不通过') DEFAULT '待审核',
  FOREIGN KEY (payment_id) REFERENCES payments(id)
);
 */

//查询审核记录
auditRouter.get('/query', (req, res) => {
  const module3Token = req.cookies['module3_token'];
  if (!module3Token) {
    res.send({
      status: 1,
      message: 'Token not found',
    });
  } else {
    const decoded = jwt.verify(module3Token, config.jwtSecretKeyM3);
    const user_id = decoded.user_id;
    var is_inspector;
    const q = `SELECT is_inspector FROM module3_users WHERE user_id = ?`;
    db.query(q, user_id, (err, results) => {
      if (err) {
        res.status(500).json({status: 1, message: 'Internal Server Error'});
      }

      if (results.length === 0) {
        res.status(404).json({status: 1, message: 'User not found'});
      }
      is_inspector = results[0].is_inspector;
      if(is_inspector === 0) {
        res.status(400).json({ status: 1, message: 'Not inspector'});
      } else {
        const date = req.query
        console.log(date)
        const query = `SELECT aud_id, aud_status, order_id, buyer_id, seller_id, amount, creation_date, order_state 
                FROM audits, module2_order
                WHERE payment_id = order_id AND creation_date like '${date.date}%';`

        db.query(query, (error, results) => {
          if (error) {
            console.error('Error during query:', error);
            return res.status(500).json({error: 'Internal Server Error'});
          } else {
            if (results.affectedRows !== 0) {
              results.forEach((item) => {
                item.creation_date = moment(item.creation_date).format('YYYY-MM-DD');
                switch (item.order_state) {
                  case 0:
                    item.order_state = "待支付"
                    break
                  case 1:
                    item.order_state = "待发货"
                    break
                  case 2:
                    item.order_state = "待收货"
                    break
                  case 3:
                    item.order_state = "已完成"
                    break
                  case 4:
                    item.order_state = "已取消"
                    break
                  default:
                    item.order_state = "未知状态"
                    break
                }
              })
              return res.json({
                status: 200,
                message: '数据查询成功',
                data: results,
                error: null,
              });
              // res.send
            } else {
              return res.json({
                status: 400,
                message: '数据查询失败',
              })
            }
          }
        });
      }

    })
  }
});

//更新审核状态
auditRouter.post('/update', (req, res) => {
  const module3Token = req.cookies['module3_token'];
  if (!module3Token) {
    res.send({
      status: 1,
      message: 'Token not found',
    });
  } else {
    const decoded = jwt.verify(module3Token, config.jwtSecretKeyM3);
    const user_id = decoded.user_id;
    var is_inspector;
    const q = `SELECT is_inspector FROM module3_users WHERE user_id = ?`;
    db.query(q, [user_id], (err, results) => {
      if (err) {
        res.status(500).json({status: 1, message: 'Internal Server Error'});
      }

      if (results.length === 0) {
        res.status(404).json({status: 1, message: 'User not found'});
      }
      is_inspector = results[0].is_inspector;
      if (is_inspector === 0) {
        res.status(400).json({status: 1, message: 'Not inspector'});
      } else {
        const query = `UPDATE audits set aud_status = '${req.body[0].audit_status}' WHERE aud_id = '${req.body[0].audit_id}';`
        db.query(query, (error, results) => {
          if (error) {
            console.error('Error during query:', error);
            return res.status(500).json({error: 'Internal Server Error'});
          } else {
            if (results.affectedRows != 0) {
              return res.json({
                status: 200,
                message: '数据更新成功',
                data: results,
                error: null,
              });
            } else {
              return res.json({
                status: 400,
                message: '数据更新失败',
              })
            }
          }
        });
      }
    })
  }
});

//获取审核记录表
auditRouter.get('/displayall', (req, res) => {
  const module3Token = req.cookies['module3_token'];
  if (!module3Token) {
    res.send({
      status: 1,
      message: 'Token not found',
    });
  } else {
    const decoded = jwt.verify(module3Token, config.jwtSecretKeyM3);
    const user_id = decoded.user_id;
    var is_inspector;
    const q = `SELECT is_inspector FROM module3_users WHERE user_id = ?`;
    db.query(q, [user_id], (err, results) => {
      if (err) {
        res.status(500).json({status: 1, message: 'Internal Server Error'});
      }
      if (results.length === 0) {
        res.status(404).json({status: 1, message: 'User not found'});
      }
      is_inspector = results[0].is_inspector;
      if (is_inspector === 0) {
        res.status(400).json({status: 1, message: 'Not inspector'});
        console.log(res)
      } else {
        const query = `SELECT aud_id, aud_status, order_id, buyer_id, seller_id, amount, creation_date, order_state 
                FROM audits, module2_order
                WHERE payment_id = order_id;`
        db.query(query, (err, results) => {
          if (err) return res.cc(err)
          //对results中的每一个datatime进行格式化
          results.forEach((item) => {
            item.creation_date = moment(item.creation_date).format('YYYY-MM-DD');
            switch (item.order_state) {
              case 0:
                item.order_state = "待支付"
                break
              case 1:
                item.order_state = "待发货"
                break
              case 2:
                item.order_state = "待收货"
                break
              case 3:
                item.order_state = "已完成"
                break
              case 4:
                item.order_state = "已取消"
                break
              default:
                item.order_state = "未知状态"
                break
            }
          })
          // console.log(results)
          res.send({
            status: 0,
            message: '数据返回成功',
            data: results,
          })
        })
      }
    })
  }
});


module.exports = auditRouter;